<template>
  <div class="spread">
    <p class="m-content overflow-line" id="J_description">{{introduce}}</p>
    <div
        class="btn-more"
        :class="isDescStatus ? 'downImg' : 'upImg'"
        v-if="isShowMore"
        :id="'J_btnmore'+index"
        @click="showmoreDesc($event)"
    ></div>
  </div>
</template>
<script>
export default {
  name: 'Spread',
  data() {
    return {
      isShowMore: false,
      isDescStatus: true,
      introduce: "",
    };
  },
  props: {
    msg: {
      type: String,
      default: ""
    },
    index: {
      type: Number,
      default: 0
    }
  },
  created() {
    this.introduce = this.msg;
    let stringWidth = this.getStringWidth(this.msg);
    if (stringWidth > 124) {
      this.isShowMore = true;
    }
  },
  methods: {
    getStringWidth(val) {
      let len = 0;
      for (let i = 0; i < val.length; i++) {
        let length = val.charCodeAt(i);
        if( length >= 0 && length <= 128 ) {
          len += 1;
        } else {
          len += 2;
        }
      }
      return len;
    },
    showmoreDesc(e) {
      let el = e.currentTarget;
      el.previousElementSibling.classList[!this.isDescStatus ? 'add' : 'remove']('overflow-line');
      el.classList[this.isDescStatus ? 'add' : 'remove']('more-collapse');
      this.isDescStatus = !this.isDescStatus;
      this.isShowMore = true;
    }
  },
  watch: {
    msg(val) {
      if(!this.isDescStatus){
        let moreDiv = document.getElementById("J_btnmore"+this.index);
        moreDiv.click();
      }
      this.introduce = val;
      let stringWidth = this.getStringWidth(this.msg);
      if (stringWidth > 124) {
        this.isShowMore = true;
      }else {
        this.isShowMore = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>

.spread {
  width: 100%;
  height: auto;
  position: relative;
  /*这两行代码可以解决大部分场景下的换行问题*/
  word-break: break-all;
  word-wrap: break-word;
  /*但在有些场景中，还需要加上下面这行代码*/
  white-space: normal;

  .m-content {
    width: 100%;
    height: auto;
    &.overflow-line {
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }
  }

  .btn-more {
    cursor: pointer;
    float: right;
    position: absolute;
    width: 10%;
    height: 20px;
    right: -12px;
    bottom: 3px;
    z-index: 999;
  }

  .upImg {
    height: 10px;
    width: 5%;
    background-image: url("~@/assets/img/bigScreen/up.svg");
    background-size: 100% 100%;
  }

  .downImg {
    height: 10px;
    width: 5%;
    background-image: url("~@/assets/img/bigScreen/down.svg");
    background-size: 100% 100%;
  }
}
</style>
